
# calendar
from datetime import date
from itertools import groupby

from django.utils.html import conditional_escape as esc
from django.utils.encoding import smart_str, smart_unicode

from tj3.models import *
from settings import *
import os, sys, shutil, re
import os.path
import subprocess
import csv
from django.core import serializers
from string import capwords
from datetime import datetime
from utility import CleanName

TASK_COLUMNS=['bsi','id',
	'scenario','start','end','duration','complete','status','pathcriticalness',]

RESOURCE_COLUMNS=['bsi','id','scenario','complete','effort','effortdone','effortleft','fte','daily{}']

def DumpTimesheet (proj):
	type = 'timesheet'
	reports=[]
	p_scenario=proj.scenario.name
	for c_scenario in proj.scenario.get_children():
		c_scenario=c_scenario.name
		headline = [proj.name, 'V1', c_scenario, type]
		id = re.sub('\s+',' ',' '.join(headline)).replace(' ','_').upper()

		# we dump a timesheet for next week and read it back to send resource email alerts
		# file name will be "id".csv
		report='''resourcereport "%s" {
					start ${now}
					end %%{${now}+1w}
					formats csv # the round trip needs CSV
					scenarios %s
					columns id, daily {}
					loadunit days
						
					# We only like to show leaf tasks for leaf resources.
					hidetask ~(isleaf() & isleaf_() & isongoing(%s))
					}''' % (id, c_scenario, c_scenario)
		reports.append((id, report))
			
	# write to a file			
	dest = os.path.join(proj.working_path,'%s.tji' % type)
	f=open(dest,'w')
	for (id,r) in reports: f.write(re.sub('\t+','\t',r)+'\n')
	f.close()
	
	# a list of expected reports
	return [id for id,report in reports]

def GetFlags (proj):
	# flags are task and resource tags
	flags = []
	for t in Task.objects.filter(project=proj): # task tags
		flags+= t.tags.all()
		# resource tags
		for r in AllocateResource.objects.filter(task=t):
			flags += r.primary.tags.all()
			if r.alternative: flags += r.alternative.tags.all()
	return list(set(flags))
	
def DumpReport (proj, columns=TASK_COLUMNS, type='taskreport', time_period=[('1w','1w')], formats=['html']):
	# get all tags
	flags = GetFlags(proj)
	
	reports = []
	report_ids = [] #[(id,format)]
	p_scenario=proj.scenario.name
	for c_scenario in proj.scenario.get_children():
		c_scenario=c_scenario.name
		
		# headline
		# naming convention:
		# PROJECT VERSION SCENARIO [TEAM][PERIOD][STATUS]
		headline = [proj.name, 'V1', p_scenario, c_scenario, type]
							
		# hidetask by filters
		filters = [(headline,'1')] # always true, this shows everything!

		# milestones
		filter_by_milestone='ismilestone(%s)' % c_scenario
		filters.append((headline+['milestone'],filter_by_milestone))
		
		# completion
		filter_completed='%s.effortleft=0' % c_scenario
		filter_incompleted='%s.effortleft>0' % c_scenario
		
		for flag in [f.name for f in flags]: # iterate all flags						
			# filter by flags/tags
			filter_by_flag=flag
			filters.append((headline+[flag],filter_by_flag))
			
			for past,future in time_period: # iterate time bands
				# filter by time band
				filter_by_time='isongoing(%s)' %c_scenario
				filters.append((headline+['%s %s' %(past,future)], filter_by_time))
				
				# filter by flag and timeband
				filter_by_flag_and_time='&'.join([filter_by_flag, filter_by_time])
				filters.append((headline+[flag, '%s %s'% (past,future)],filter_by_flag_and_time))
			
				for ft in formats: # iterate all formats
					# we customize:
					# report id
					# report file name
					# headline
					# filter (hidetask)
					report_body = '''start %%{${now}-%s}
									end %%{${now}+%s}
									formats %s
									scenarios %s
									sorttasks tree, %s.start.up
									timeformat "%%a %s"
									loadunit shortauto
									columns %s
									''' % (past,future,ft,','.join([p_scenario,c_scenario]),
											c_scenario, # sort by children scenario.start.up
											proj.timeformat,
											','.join(columns),)
					
					for hl,filter in filters:
						id = re.sub('\s+',' ',' '.join(hl)).replace(' ','_').upper()
						hl = ' - '.join(hl).upper()
						
						# report filename will be "id".format
						report = '''%s "%s" {
									%s # report body
									headline "%s"	
									hidetask ~(%s)
									}
									''' % (type, id, report_body, hl, filter,)
						reports.append((id,report))
						report_ids.append((id,ft))
						
	# write to a file			
	dest = os.path.join(proj.working_path,'%s.tji'%type)
	f=open(dest,'w')
	f.write('flags '+','.join([a.name for a in flags])+'\n')
	for (id,r) in reports: f.write(re.sub('\t+','\t',r)+'\n')
	f.close()
	
	# a list of expected reports
	return report_ids

